package com.example.guardian.home;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.DisplayUtils;

public class setHeight {
    /**
     * 动态设置GridView的高度
     * @param gridView
     */
    public static void setGridViewHeight(Context content, GridView gridView) {
        // 获取gridview的adapter
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = gridView.getNumColumns();// 或者gridView.getNumColumns();
        int totalHeight = 0;
        // i每次加3，相当于listAdapter.getCount()小于等于3时 循环一次，计算一次item的高度
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, gridView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight()+ DisplayUtils.dip2px(content,10);
        }
        Log.d("height", String.valueOf(totalHeight));
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        Log.d("height", String.valueOf(totalHeight));
        // 设置高度
        params.height = totalHeight;
        // 设置参数
        gridView.setLayoutParams(params);
    }
    public static void setListViewHeight(ListView listView) {
        //获取listview的适配器
        ListAdapter listAdapter = listView.getAdapter(); //item的高度
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listView.getAdapter().getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高 //统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight()+listView.getDividerHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;
        listView.setLayoutParams(params);
    }
}
